<?php

namespace App\Model;

use App\BaseModel;
use Illuminate\Support\Facades\DB;

class UserCoupon extends BaseModel
{
    protected $table = "t_user_coupons";

    protected $fillable = [
        'code',
        'get_user_id',
        'coupon_id',
        'has_used',
        'state',
        'used_at',
        'expired_at'
    ];

    public function coupon()
    {
        return $this->belongsTo('App\Model\WineCoupon','coupon_id','id');
    }

    public function user()
    {
        return $this->belongsTo('App\User','get_user_id','id');
    }

    public function order()
    {
        return $this->belongsTo('App\Model\Order','order_id','id');
    }

    //检查用户是否可以使用优惠券
    public static function checkCanUse($userCoupon,$user,$total,$product_id)
    {
        if ($userCoupon->get_user_id != $user->id) {
            return ['success'=>false,'error'=>'优惠券无效'];
        }
        if ($userCoupon->state == 1 || $userCoupon->order_id>0){
            return ['success'=>false,'error'=>'优惠券已被使用'];
        }

        if (strtotime($userCoupon->expired_at) < time()) {
            $userCoupon->state = 2;
            $userCoupon->save();
            return ['success'=>false,'error'=>'优惠券已过期'];
        }

        $c = $userCoupon->coupon;
        if (!$c) return ['success'=>false,'error'=>'优惠券无效'];

        if ($c->enable_use_date == "yes" && strtotime($c->can_use_start) > time()){
            return ['success'=>false,'error'=>'优惠券暂未到使用日期'];
        }

        $cc = $c->category;
        if(!$cc) return ['success'=>false,'error'=>'优惠券无效'];
        if ($cc->loseType == "full" && $total<$cc->full_amount){
            return ['success'=>false,'error'=>'订单未达到满减金额'];
        }

        switch ($cc->category)
        {
            case "product":
                if ($cc->product_id != $product_id) {
                    return ['success'=>false,'error'=>'优惠券只能在指定商品内使用'];
                }
                break;
            case "importer":
                if (!WineProduct::checkImporterExist($cc->importer_id,$product_id)){
                    return ['success'=>false,'error'=>'优惠券只能在指定进口商内使用'];
                }
                break;
            case "dealer":
                if (!WineProduct::checkDealerExist($cc->dealer_id,$product_id)){
                    return ['success'=>false,'error'=>'优惠券只能在指定经销商内使用'];
                }
                break;
            default:
                break;
        }

        if ($cc->amount > $total) {
            return ['success'=>false,'error'=>'优惠券无效'];
        }

        return  ['success'=>true];
    }

    //更新到期时间
    public function updateExpiredAt()
    {
        $create = strtotime($this->created_at);
        $coupon = $this->coupon;

        if($coupon){
            //是否开启使用期限日期范围条件
            if ($coupon->enable_use_date == "yes"){
                $expire = $coupon->can_use_end;
            }
            //是否开启使用期限多少天条件
            elseif ($coupon->enable_use_days == "yes"){
                $expire = date('Y-m-d',strtotime("+ ".($coupon->can_use_days-1)."days",strtotime($this->created_at)));
            }else{
                $expire = date('Y-m-d');
            }
        }
        $this->expired_at = $expire;
        $this->save();
    }

    public static function listCanUse($user_id,$product_id=false)
    {
        UserCoupon::closeExpired();

        $items = DB::table('wine_coupons')->rightJoin('t_user_coupons','t_user_coupons.coupon_id','=','wine_coupons.id')
            ->leftJoin('wine_coupon_categories','wine_coupon_categories.id','=','wine_coupons.coupon_category_id')
            ->where('t_user_coupons.get_user_id','=',$user_id)
            ->where('t_user_coupons.state','=',0)
            ->whereNull('wine_coupons.deleted_at')
            ->select(['t_user_coupons.id','t_user_coupons.state','t_user_coupons.used_at','wine_coupons.enable_use_date',
                'wine_coupons.can_use_start','wine_coupons.can_use_end','wine_coupons.enable_use_days','wine_coupons.can_use_days',
                't_user_coupons.expired_at','t_user_coupons.created_at','wine_coupons.coupon_name','wine_coupons.name',
                'wine_coupon_categories.amount','wine_coupon_categories.product_id','wine_coupon_categories.category',
                'wine_coupon_categories.loseType','wine_coupon_categories.importer_id','wine_coupon_categories.dealer_id',
                'wine_coupon_categories.full_amount','t_user_coupons.order_id'])
            ->orderBy('t_user_coupons.expired_at','asc')
            ->get();

        if ($product_id) {
            $dealerIds = WineProduct::listDealerIds($product_id);
            $importerIds = WineProduct::listImporterIds($product_id);

            $items = $items->filter(function ($v) use ($product_id,$dealerIds,$importerIds){
                $bool = false;
                switch ($v->category)
                {
                    case "general":
                        $bool = true;
                        break;
                    case "product":
                        $bool = $product_id == $v->product_id;
                        break;
                    case "importer":
                        $bool = in_array($v->importer_id,$importerIds);
                        break;
                    case "dealer":
                        $bool = in_array($v->dealer_id,$dealerIds);
                        break;
                    default:
                        $bool = false;
                        break;
                }
                if ($bool && $v->enable_use_date == "yes" && (strtotime($v->can_use_start) > time()|| strtotime($v->can_use_end) < time()) ) {
                    $bool = false;
                }
                return $bool;
            });
            $items = $items->values();
        }

        $items = $items->map(function($item){
            $item->amount = floatval($item->amount);
            $item->full_amount = floatval($item->full_amount);
            return $item;
        });
        return $items;
    }

    //更新统计
    public function updateCouponCount()
    {
        return WineCoupon::updateChatByCouponId($this->coupon_id);
    }

    //更新状态根据订单取消
    public static function updateWhenOrderCancelByIds($orderIds)
    {
        if (count($orderIds) > 0 ){
            $res = DB::select('select coupon_id from t_user_coupons where state=1 and 
                order_id in ('.implode(',',$orderIds).') group by coupon_id');

            foreach ($res as $row) {
                WineCoupon::updateChatByCouponId($row->coupon_id);
            }

            return DB::table('t_user_coupons')->whereIn('order_id',$orderIds)->update(['order_id'=>0,'state'=>0]);
        }

        return false;
    }

    public static function closeExpired()
    {
        $t = date('Y-m-d');
        return DB::select('update t_user_coupons set state=2 where expired_at<"'.$t.'"');
    }

    //获取优惠券
    public static function getCoupons($userId,$couponIds,$origin='')
    {
        $ids = explode(',',$couponIds);

        $ids = DB::table('wine_coupons')->where('sku','>',0)->whereIn('id',$ids)
            ->where('can_get_start','<=',date('Y-m-d'))
            ->where('can_get_end','>=',date('Y-m-d'))
            ->pluck('id');

        foreach ($ids as $id){
            $m = new UserCoupon();
            $m->get_user_id = $userId;
            $m->coupon_id = $id;
            $m->origin = $origin;
            $m->save();
            $m->updateExpiredAt();

            $m->coupon->sku -=1;
            $m->coupon->get +=1;
            $m->coupon->last_count = $m->coupon->sku - $m->coupon->get;
            $m->coupon->save();
        }
        return count($ids);
    }
}
